package com.xique.door.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.text.Convert;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.*;
import com.xique.door.bean.request.commandV1.*;
import com.xique.door.bean.search.PermissionGroupDeviceListSearch;
import com.xique.door.bean.search.PermissionGroupSelectUserSearch;
import com.xique.door.bean.transfer.UserPersonConvert;
import com.xique.door.biz.service.IDeviceCommandNewService;
import com.xique.door.constant.AccessCommandConstant;
import com.xique.door.constant.UserConstant;
import com.xique.door.device.command.AccessCommandHQService;
import com.xique.door.device.freeview.constant.CommandCardType;
import com.xique.door.device.freeview.service.biz.FreeviewCommandBizService;
import com.xique.door.device.hk.bean.param.*;
import com.xique.door.device.hk.bean.response.BasicResponse;
import com.xique.door.device.hk.bean.response.PermissionGroupResponse;
import com.xique.door.device.hk.bean.response.PersonResponse;
import com.xique.door.device.hk.service.HikAccessCommandService;
import com.xique.door.device.hk.service.HkCommandService;
import com.xique.door.device.hq.bean.dto.HQResultDTO;
import com.xique.door.device.hq.bean.dto.HQResultDataDTO;
import com.xique.door.event.*;
import com.xique.door.mapper.UserMapper;
import com.xique.door.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.SingletonMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shd
 * @create 2021/7/7 15:57
 */
@Service
@Slf4j
@Deprecated
public class DeviceCommandNewServiceImpl implements IDeviceCommandNewService {

    @Value("${validateCode}")
    private String validateCode;

    @Value("${HQ_DEFAULT_PIC}")
    private String hqDefaultPic;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IVisitorService visitorService;

    @Autowired
    private IPermissionGroupDeviceService permissionGroupDeviceService;

    @Autowired
    private IPermissionGroupUserService permissionGroupUserService;

    @Autowired
    private IAccessDeviceService accessDeviceService;

    @Autowired
    private AccessCommandHQService accessCommandService;

    @Autowired
    private IUserDeviceService userDeviceService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private IPermissionGroupService permissionGroupService;

    @Autowired
    private HikAccessCommandService hikAccessCommandService;

    @Autowired
    private HkCommandService hkCommandService;

    @Autowired
    private UserPersonConvert userPersonConvert;

    @Autowired
    private FreeviewCommandBizService freeviewCommandBizService;

    @Autowired
    private AccessCommandHQService accessCommandHQService;

    /**
     * 下发单用户信息到设备（单个/多个）
     * @author shd
     * @date 2021/7/7 16:00
     * @param request
     */
    @Override
    public AjaxResult userInfoDownload(DeviceCommandUserInfoDownloadRequest request) {
        if (UserConstant.Type.USER.equals(request.getUserType())) {
            return this.userDownload(request);
        } else {
            return this.visitorDownload(request);
        }
    }

    @Override
    public AjaxResult userCardInfoDownload(DeviceCommandUserInfoDownloadRequest request, DCard dCard, String commandType) {
        return this.userCardDownload(request,dCard,commandType);
    }

    @Override
    public AjaxResult updateUserInfo(User user) {
        //查出用户的设备如果含海康的,调用更新用户基础信息
        List<AccessDevice> accessDeviceList =   accessDeviceService.selectAccessDeviceListByUser( user);
        List<AccessDevice> hqDeviceList = accessDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getModel())).collect(Collectors.toList());
        List<AccessDevice> hkDeviceList = accessDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HK.equals(item.getModel())).collect(Collectors.toList());
        List<AccessDevice> freeviewDeviceList = accessDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.FREEVIEW_45.equals(item.getModel())).collect(Collectors.toList());
        if (!hkDeviceList.isEmpty()){
            this.addUpdateHkPersonBaseInfo(user,"update",true);
        }
        if (!hqDeviceList.isEmpty()){
            List<String> devSns = hqDeviceList.stream().map(AccessDevice::getDevSn).collect(Collectors.toList());
            //异步下发需要更新的用户到设备
            applicationContext.publishEvent(new AddUserCommandEvent(devSns, user));
        }

        if (!freeviewDeviceList.isEmpty()){
//            //全视通无法修改照片，每次下发都会给用户新增一个照片,所以下发前判断用户是否成功下发过，如果成功下发过需要从设备先删除
            List<String> devSns = freeviewDeviceList.stream().map(AccessDevice::getDevSn).collect(Collectors.toList());
//            JSONObject batchCustomIdStatus = freeviewRedisUtil.getBatchCustomIdStatus(User.class.getSimpleName(), devSns, Collections.singletonList(user.getCustomId()));
//            JSONArray jsonArray = batchCustomIdStatus.getJSONArray(user.getCustomId());
//            List<FreeviewCommandResultDto> freeviewCommandResultDtos = JSON.parseArray(jsonArray.toJSONString(), FreeviewCommandResultDto.class);
//            List<String> deleteDevSns = freeviewCommandResultDtos.stream().filter(e -> CommandStatus.SUCCESS.equals(e.getStatus())).map(FreeviewCommandResultDto::getDevice_code).collect(Collectors.toList());
//            freeviewCommandBizService.deleteUserInfo(deleteDevSns,user);
            //删除后再下发新照片
            Object o = freeviewCommandBizService.downUserInfo(devSns, user);
            return this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
        }
        return AjaxResult.success();
    }

    /**
     * 用户信息下发
     * @author shd
     * @date 2021/7/8 9:47
     * @param request
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    private AjaxResult userDownload(DeviceCommandUserInfoDownloadRequest request) {
        Long userId = request.getUserId();
        User user = userMapper.selectUserById(userId);

        List<Long> groupIds = new ArrayList<>();
        if (null == request.getGroupId()) {
            //人员列表下发人员
            PermissionGroupSelectUserSearch selectUserSearch = new PermissionGroupSelectUserSearch();
            selectUserSearch.setUserIds(Collections.singletonList(userId));
            List<PermissionGroupUser> permissionGroupUserList = permissionGroupUserService.selectPermissionGroupUserListBySearch(selectUserSearch);
            groupIds.addAll(permissionGroupUserList.stream().map(PermissionGroupUser::getGroupId).collect(Collectors.toList()));
        } else {
            //权限组下发人员
            groupIds.add(request.getGroupId());
        }

        List<PermissionGroupDevice> permissionGroupDeviceList = permissionGroupDeviceService.selectPermissionGroupDeviceListByGroupIds(groupIds);

        List<PermissionGroupDevice> hkPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HK.equals(item.getDevModel())).collect(Collectors.toList());
        List<PermissionGroupDevice> hqPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getDevModel())).collect(Collectors.toList());
        List<PermissionGroupDevice> freeviewPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.FREEVIEW_45.equals(item.getDevModel())).collect(Collectors.toList());

        if (!hkPermissionGroupDeviceList.isEmpty()) {
            List<String> hkGroupIds = hkPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getHkGroupId).distinct().collect(Collectors.toList());
            for (String hkGroupId : hkGroupIds) {
                HikPersonAddPermissionGroupParam param = new HikPersonAddPermissionGroupParam();
                param.setGroupId(hkGroupId);
                param.setEmployeeNos(Collections.singletonList(user.getCustomId()));
                hikAccessCommandService.addPersons(param);
            }
        }

        if (!hqPermissionGroupDeviceList.isEmpty()) {
            List<String> devSns = hqPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDevSn).collect(Collectors.toList());

            if (request.isAsync()) {
                // 异步操作
                applicationContext.publishEvent(new AddUserCommandEvent(devSns, user));
//                return AjaxResult.success();
            }
            Object o = accessCommandService.downCardInfos(devSns, user, AccessCommandConstant.VERSION);

            AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
            if (AjaxResult.isError(returnHQ)){
                return returnHQ;
            }
        }

        if (!freeviewPermissionGroupDeviceList.isEmpty()){
            List<String> devSns = freeviewPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDevSn).collect(Collectors.toList());
            Object o = freeviewCommandBizService.downUserInfo(devSns, user);
            AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
            if (AjaxResult.isError(returnHQ)){
                return returnHQ;
            }
        }

        return AjaxResult.success();
    }

    /**
     * 卡片信息下发
     * @param request commandType(区分卡片下发时是删除还是新增)
     * @return
     */
    private AjaxResult userCardDownload(DeviceCommandUserInfoDownloadRequest request,DCard dCard,String commandType) {
        Long userId = request.getUserId();
        User user = userMapper.selectUserById(dCard.getUserId());
        user.setCustomId(dCard.getCustomId());
        if(StringUtils.isEmpty(user.getFaceUrl())){
           user.setFaceUrl(hqDefaultPic);
        }
        List<Long> groupIds = new ArrayList<>();
        if (null == request.getGroupId()) {
            PermissionGroupSelectUserSearch selectUserSearch = new PermissionGroupSelectUserSearch();
            selectUserSearch.setUserIds(Collections.singletonList(userId));
            List<PermissionGroupUser> permissionGroupUserList = permissionGroupUserService.selectPermissionGroupUserListBySearch(selectUserSearch);
            groupIds.addAll(permissionGroupUserList.stream().map(PermissionGroupUser::getGroupId).collect(Collectors.toList()));
        } else {
            groupIds.add(request.getGroupId());
        }

        List<PermissionGroupDevice> permissionGroupDeviceList = permissionGroupDeviceService.selectPermissionGroupDeviceListByGroupIds(groupIds);

        List<PermissionGroupDevice> hkPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HK.equals(item.getDevModel())).collect(Collectors.toList());
        List<PermissionGroupDevice> hqPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getDevModel())).collect(Collectors.toList());
        List<PermissionGroupDevice> freeviewPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.FREEVIEW_45.equals(item.getDevModel())).collect(Collectors.toList());


        if (!hkPermissionGroupDeviceList.isEmpty()) {
            List<String> hkGroupIds = hkPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getHkGroupId).distinct().collect(Collectors.toList());
            for (String hkGroupId : hkGroupIds) {
                HikPersonAddPermissionGroupParam param = new HikPersonAddPermissionGroupParam();
                param.setGroupId(hkGroupId);
                param.setEmployeeNos(Collections.singletonList(user.getCustomId()));
                hikAccessCommandService.addPersons(param);
            }
        }

        if (!hqPermissionGroupDeviceList.isEmpty()) {
            List<String> devSns = hqPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDevSn).collect(Collectors.toList());

            if (request.isAsync()) {
                // 异步操作
                applicationContext.publishEvent(new AddUserCommandEvent(devSns, user));
//                return AjaxResult.success();
            }

//            Object o = accessCommandService.downCardInfos(devSns, user, dCard,AccessCommandConstant.VERSION);
//            AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
//            if (AjaxResult.isError(returnHQ)){
//                return returnHQ;
//            }

//            return this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
        }

        if (!freeviewPermissionGroupDeviceList.isEmpty()){
            List<String> devSns = freeviewPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDevSn).collect(Collectors.toList());
            Object commandReturnObj = null;
            if (CommandCardType.DOWN_CARD.equals(commandType)){
                //新增
//                commandReturnObj = freeviewCommandBizService.downCardInfo(devSns, dCard);
            }else if (CommandCardType.DELETE_CARD.equals(commandType)){
                 dCard.setCardSn(dCard.getOriginCardSn());
                commandReturnObj = freeviewCommandBizService.deleteCardInfo(devSns, dCard);
            }else if (CommandCardType.UPDATE_CARD.equals(commandType) ){
                commandReturnObj = freeviewCommandBizService.updateCardInfo(devSns,dCard);
            }else if (CommandCardType.LOSS_CARD.equals(commandType) ){
                commandReturnObj = freeviewCommandBizService.lostCardInfo(devSns,dCard);
            }
            AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(commandReturnObj.toString(), HQResultDTO.class), request.getFromType());
            if (AjaxResult.isError(returnHQ)){
                return returnHQ;
            }
        }

        return AjaxResult.success();
    }

    /**
     * 访客信息下发
     * @author shd
     * @date 2021/7/8 9:47
     * @param request
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    private AjaxResult visitorDownload(DeviceCommandUserInfoDownloadRequest request) {
        Long visitorId = request.getUserId();
        Visitor visitor = visitorService.selectVisitorById(visitorId);
        Long userId = visitor.getUserId();

        List<PermissionGroupDevice> permissionGroupDeviceList = this.getGroupDeviceByUserIdAndGroupId(userId, request.getGroupId());
        List<PermissionGroupDevice> hqPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getDevModel())).collect(Collectors.toList());
        List<PermissionGroupDevice> freeviewPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.FREEVIEW_45.equals(item.getDevModel())).collect(Collectors.toList());
        if (!hqPermissionGroupDeviceList.isEmpty()) {
            List<String> devSns = hqPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDevSn).collect(Collectors.toList());

            if (request.isAsync()) {
                // 异步操作
                applicationContext.publishEvent(new AddVisitorCommandEvent(devSns, visitor));
                return AjaxResult.success();
            }
            Object o = accessCommandService.downVisitorInfos(devSns, visitor, AccessCommandConstant.VERSION);
            AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
            if (AjaxResult.isError(returnHQ)){
                return returnHQ;
            }
        }
        if (!freeviewPermissionGroupDeviceList.isEmpty()){
            List<String> devSns = freeviewPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDevSn).collect(Collectors.toList());
            Object o = freeviewCommandBizService.downVisitorInfo(devSns, visitor);
            AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
            if (AjaxResult.isError(returnHQ)){
                return returnHQ;
            }
        }
        return AjaxResult.success();
    }

    /**
     * 获取下发的设备编号
     * @author shd
     * @date 2021/7/8 9:48
     * @param userId 用户ID
     * @param groupId 权限组ID
     * @return java.util.List<java.lang.String>
     */
//    private List<String> getDownloadDevSn(Long userId, Long groupId) {
//        List<Long> deviceIds = this.getDeviceId(userId, groupId);
//
//        List<AccessDevice> accessDeviceList = accessDeviceService.selectAccessDeviceByIds(deviceIds, AccessDeviceConstant.DeviceStatus.NORMAL);
//
//        return accessDeviceList.stream().map(AccessDevice::getDevSn).distinct().collect(Collectors.toList());
//    }

    /**
     * 获取删除的设备编号
     * @author shd
     * @date 2021/7/8 9:48
     * @param userIds 用户ID
     * @param groupId 权限组ID
     * @return java.util.List<java.lang.String>
     */
    private List<UserDevice> getDelUserDevice(List<Long> userIds, Long groupId) {
        List<Long> groupIds = new ArrayList<>();
        if (null == groupId) {
            PermissionGroupSelectUserSearch selectUserSearch = new PermissionGroupSelectUserSearch();
            selectUserSearch.setUserIds(userIds);
            List<PermissionGroupUser> permissionGroupUserList = permissionGroupUserService.selectPermissionGroupUserListBySearch(selectUserSearch);
            groupIds.addAll(permissionGroupUserList.stream().map(PermissionGroupUser::getGroupId).distinct().collect(Collectors.toList()));
        } else {
            groupIds.add(groupId);
        }

        PermissionGroupDeviceListSearch deviceListSearch = new PermissionGroupDeviceListSearch();
        deviceListSearch.setGroupIds(groupIds);
        List<PermissionGroupDevice> permissionGroupDeviceList = permissionGroupDeviceService.selectPermissionGroupDeviceListBySearch(deviceListSearch);

        List<Long> deviceIds = permissionGroupDeviceList.stream().map(PermissionGroupDevice::getDeviceId).distinct().collect(Collectors.toList());

        return userDeviceService.selectUserDeviceListByUserIdsAndDeviceIds(null, userIds, deviceIds);
    }

    /**
     * 获取下发的设备ID
     * @author shd
     * @date 2021/7/8 9:48
     * @param userId 用户ID
     * @param groupId 权限组ID
     * @return java.util.List<java.lang.String>
     */
    private List<PermissionGroupDevice> getGroupDeviceByUserIdAndGroupId(Long userId, Long groupId) {
        List<Long> groupIds = new ArrayList<>();
        if (null == groupId) {
            PermissionGroupSelectUserSearch selectUserSearch = new PermissionGroupSelectUserSearch();
            selectUserSearch.setUserIds(Collections.singletonList(userId));
            List<PermissionGroupUser> permissionGroupUserList = permissionGroupUserService.selectPermissionGroupUserListBySearch(selectUserSearch);
            groupIds.addAll(permissionGroupUserList.stream().map(PermissionGroupUser::getGroupId).distinct().collect(Collectors.toList()));
        } else {
            groupIds.add(groupId);
        }
        return permissionGroupDeviceService.selectPermissionGroupDeviceListByGroupIds(groupIds);
    }

    /**
     * 获取返回值
     * @author shd
     * @date 2021/7/8 9:48
     * @param dto
     * @param fromType 来源类型
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    private AjaxResult getReturnHQ(HQResultDTO dto, String fromType) {
        if (0 != dto.getResult_code()) {
            return AjaxResult.error("下发失败");
        }
        List<String> successMsgList = new ArrayList<>();
        List<String> errorMsgList = new ArrayList<>();

        if(null != dto && null != dto.getData()){
            for (HQResultDataDTO data : dto.getData()) {
                String message = "";
                if (!data.getStatus().equals(AccessCommandConstant.DeviceStatus.SUCCESS)) {
                    message = data.getDeviceCode() + ":" + data.getMsg() + (data.getResult() != null ?  " 具体原因：" + data.getResult().getInfo().getDetail() : "") + "<br/>";
                    errorMsgList.add(message);
                } else {
                    message = data.getDeviceCode() + ":" + data.getMsg() + "<br/>";
                    successMsgList.add(message);
                }
            }
        }
        //TODO
        if(null != dto && null != dto.getData_obj()){

        }
        String successMsg = StringUtils.join(successMsgList, "");
        String errorMsg = StringUtils.join(errorMsgList, "");
        StringBuilder returnMsg = new StringBuilder();
        if (StringUtils.isNotEmpty(errorMsg)){
            returnMsg.append("失败下发设备如下：<br/>" + errorMsg + "<br/>");
        }
        if (StringUtils.isNotEmpty(successMsg)){
            returnMsg.append( "成功下发设备如下：<br/>" + successMsg);
        }
//        String returnMsg = "失败下发设备如下：<br/>" + errorMsg +  "<br/>成功下发设备如下：<br/>" + successMsg;
        if (AccessCommandConstant.FromType.APP.equals(fromType)) {
            StringUtils.replace(returnMsg.toString(), "<br/>", "\n");
        }
        if (!errorMsgList.isEmpty()) {
            return AjaxResult.success(returnMsg.toString());
        }
        return AjaxResult.success(returnMsg.toString());
    }

    /**
     * 下发批量用户信息到设备（单个/多个）目前只支持权限组批量下发
     * @author shd
     * @date 2021/7/8 9:50
     * @param request
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @Override
    public AjaxResult userInfosDownload(DeviceCommandUserInfoDownloadRequest request) {
        Long groupId = request.getGroupId();
        if (request.getUserIds().isEmpty()) {
           List<PermissionGroupUser> permissionGroupUserList = permissionGroupUserService.selectPermissionGroupUserListByGroupIds(Collections.singletonList(groupId));
           request.setUserIds(permissionGroupUserList.stream().map(PermissionGroupUser::getUserId).distinct().collect(Collectors.toList()));
        }
        List<Long> userIds = request.getUserIds();
        List<User> userList = userMapper.selectUserByIds(userIds, UserConstant.Status.NORMAL);

        List<PermissionGroupDevice> permissionGroupDeviceList = permissionGroupDeviceService.selectPermissionGroupDeviceListByGroupIds(Collections.singletonList(groupId));

        List<PermissionGroupDevice> hkPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HK.equals(item.getDevModel())).distinct().collect(Collectors.toList());
        List<PermissionGroupDevice> hqPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getDevModel())).collect(Collectors.toList());
        List<PermissionGroupDevice> freeviewPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.FREEVIEW_45.equals(item.getDevModel())).collect(Collectors.toList());


        if (!hkPermissionGroupDeviceList.isEmpty()) {
            List<String> hkGroupIds = hkPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getHkGroupId).distinct().collect(Collectors.toList());
            for (String hkGroupId : hkGroupIds) {
                HikPersonAddPermissionGroupParam param = new HikPersonAddPermissionGroupParam();
                param.setGroupId(hkGroupId);
                param.setEmployeeNos(userList.stream().map(User::getCustomId).collect(Collectors.toList()));
                hikAccessCommandService.addPersons(param);
            }
        }

        if (!hqPermissionGroupDeviceList.isEmpty()) {
            List<String> devSns = hqPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDevSn).collect(Collectors.toList());

            if (request.isAsync()) {
                // 异步操作
                applicationContext.publishEvent(new AddUserBatchCommandEvent(devSns, userList));
//                return AjaxResult.success();
            }
//
//            Object o = accessCommandService.downBatchUserInfos(devSns, userList, AccessCommandConstant.VERSION);
//
//            AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
//            if (AjaxResult.isError(returnHQ)){
//                return returnHQ;
//            }

//            return this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
        }

//        if (!freeviewPermissionGroupDeviceList.isEmpty()){
//            freeviewPermissionGroupDeviceList.forEach(e ->{
//                Object o =  freeviewCommandBizService.downUsers(e,userList);
//            });
//        }
//        if (!freeviewPermissionGroupDeviceList.isEmpty()){
//            List<String> devSns = freeviewPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDevSn).collect(Collectors.toList());
//            Object o = freeviewCommandBizService.downCardInfos(devSns, userList);
//            AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
//            if (AjaxResult.isError(returnHQ)){
//                return returnHQ;
//            }
//        }

        return AjaxResult.success();
    }

    /**
     * 删除单个用户信息到设备（单个/多个）
     * @author shd
     * @date 2021/7/8 10:22
     * @param request
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @Override
    public AjaxResult permissionUserInfoDel(DeviceCommandUserInfoDelRequest request) {
        if (UserConstant.Type.USER.equals(request.getUserType())) {
            return this.permissionUserDel(request);
        } else {
            return this.visitorDel(request);
        }
    }

    /**
     * 用户信息删除
     * @author shd
     * @date 2021/7/8 10:52
     * @param request
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    private AjaxResult permissionUserDel(DeviceCommandUserInfoDelRequest request) {
        Long userId = request.getUserId();
        User user = userMapper.selectUserById(userId);

        List<PermissionGroupDevice> permissionGroupDeviceList = permissionGroupDeviceService.selectPermissionGroupDeviceListByGroupIds(Collections.singletonList(request.getGroupId()));

        List<PermissionGroupDevice> hkPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HK.equals(item.getDevModel())).collect(Collectors.toList());
        List<PermissionGroupDevice> hqPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getDevModel())).collect(Collectors.toList());
        List<PermissionGroupDevice> freeviewPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.FREEVIEW_45.equals(item.getDevModel())).collect(Collectors.toList());


        if (!hkPermissionGroupDeviceList.isEmpty()) {
            List<String> hkGroupIds = hkPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getHkGroupId).distinct().collect(Collectors.toList());
            for (String p : hkGroupIds) {
                HikPersonDelPermissionGroupParam param = new HikPersonDelPermissionGroupParam();
                param.setGroupId(p);
                param.setEmployeeNos(Collections.singletonList(user.getCustomId()));
                hikAccessCommandService.delPersons(param);
            }
        }

        if (!hqPermissionGroupDeviceList.isEmpty()) {
            List<UserDevice> userDeviceList = userDeviceService.selectUserDeviceListByUserIdsAndDeviceIds(null, Collections.singletonList(userId), hqPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDeviceId).collect(Collectors.toList()));
            List<String> devSns = userDeviceList.stream().map(UserDevice::getDevSn).distinct().collect(Collectors.toList());

            Map<String, String> userMap = new HashMap<>();
            userMap.put("customId", user.getCustomId());

            if (request.isAsync()) {
                // 异步操作
                applicationContext.publishEvent(new DelUserCommandEvent(devSns, Collections.singletonList(user.getCustomId())));
//                return AjaxResult.success();
            }

            Object o = accessCommandService.delUserInfos(devSns, userMap, AccessCommandConstant.VERSION);

             AjaxResult returnHQ =  this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
            if (AjaxResult.isError(returnHQ)){
                return returnHQ;
            }
        }

        if (!freeviewPermissionGroupDeviceList.isEmpty()){
            List<String> devSns = freeviewPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDevSn).collect(Collectors.toList());
            Object o = freeviewCommandBizService.deleteUserInfo(devSns, user);
            AjaxResult returnHQ =  this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
            if (AjaxResult.isError(returnHQ)){
                return returnHQ;
            }
        }

        return AjaxResult.success();


    }

    /**
     * 访客信息删除
     * @author shd
     * @date 2021/7/8 10:52
     * @param request
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    private AjaxResult visitorDel(DeviceCommandUserInfoDelRequest request) {
        Long visitorId = request.getUserId();
        Visitor visitor = visitorService.selectVisitorById(visitorId);
        Long userId = visitor.getUserId();
        List<PermissionGroupDevice> permissionGroupDeviceList = this.getGroupDeviceByUserIdAndGroupId(userId, request.getGroupId());
        List<PermissionGroupDevice> hqPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getDevModel())).collect(Collectors.toList());
        List<PermissionGroupDevice> freeviewPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.FREEVIEW_45.equals(item.getDevModel())).collect(Collectors.toList());
        if (!hqPermissionGroupDeviceList.isEmpty()){
            List<String> devSns = hqPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDevSn).collect(Collectors.toList());

            Map<String, String> userMap = new HashMap<>();
            userMap.put("customId", visitor.getCustomId());

            if (request.isAsync()) {
                // 异步操作
                applicationContext.publishEvent(new DelUserCommandEvent(devSns, Collections.singletonList(visitor.getCustomId())));
            }

            Object o = accessCommandService.delUserInfos(devSns, userMap, AccessCommandConstant.VERSION);

            AjaxResult returnHQ =  this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
            if (AjaxResult.isError(returnHQ)){
                return returnHQ;
            }
        }
        if (!freeviewPermissionGroupDeviceList.isEmpty()){
            List<String> devSns = freeviewPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDevSn).collect(Collectors.toList());
            Object o = freeviewCommandBizService.deleteVisitorInfo(devSns, visitor);
            AjaxResult returnHQ =  this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), request.getFromType());
            if (AjaxResult.isError(returnHQ)){
                return returnHQ;
            }
        }
        return AjaxResult.success("删除成功");
    }

    /**
     * 删除多个用户信息到设备（单个/多个）
     * @author shd
     * @date 2021/7/8 11:06
     * @param request
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @Override
    public AjaxResult permissionUserInfosDel(DeviceCommandUserInfoDelRequest request) {
        if (UserConstant.Type.USER.equals(request.getUserType())) {
            return this.permissionUsersDel(request);
        } else {
            return this.visitorsDel(request);
        }
    }

    /**
     * 多个用户信息删除
     * @author shd
     * @date 2021/7/8 11:46
     * @param request
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    private AjaxResult permissionUsersDel(DeviceCommandUserInfoDelRequest request) {
        Long groupId = request.getGroupId();
        List<Long> userIds = request.getUserIds();
        List<User> userList = userMapper.selectUserByIds(userIds,UserConstant.Status.NORMAL);

        List<PermissionGroupDevice> permissionGroupDeviceList = permissionGroupDeviceService.selectPermissionGroupDeviceListByGroupIds(Collections.singletonList(groupId));

        List<PermissionGroupDevice> hkPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HK.equals(item.getDevModel())).collect(Collectors.toList());
        List<PermissionGroupDevice> hqPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getDevModel())).collect(Collectors.toList());
        List<PermissionGroupDevice> freeviewPermissionGroupDeviceList = permissionGroupDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.FREEVIEW_45.equals(item.getDevModel())).collect(Collectors.toList());


        if (!hkPermissionGroupDeviceList.isEmpty()) {
            List<String> hkGroupIds = hkPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getHkGroupId).distinct().collect(Collectors.toList());
            for (String p : hkGroupIds) {
                HikPersonDelPermissionGroupParam param = new HikPersonDelPermissionGroupParam();
                param.setGroupId(p);
                param.setEmployeeNos(userList.stream().map(User::getCustomId).collect(Collectors.toList()));
                hikAccessCommandService.delPersons(param);
            }
        }

        if (!hqPermissionGroupDeviceList.isEmpty()) {
            Map<Long, String> customIdMap = userList.stream().collect(Collectors.toMap(User::getId, User::getCustomId));

            List<UserDevice> userDeviceList = this.getDelUserDevice(userIds, groupId);

            Map<String, List<String>> userMap = new HashMap<>();
            userDeviceList.forEach(item -> {
                userMap.computeIfAbsent(item.getDevSn(), k -> new ArrayList<>());
                List<String> list = userMap.get(item.getDevSn());
                list.add(customIdMap.get(item.getUserId()));
                userMap.put(item.getDevSn(), list);
            });

            if (request.isAsync()) {
                applicationContext.publishEvent(new DelUserBatchCommandEvent(userMap));
//                return AjaxResult.success();
            }

            for (String devSn : userMap.keySet()) {
                Map<String, List<String>> customIdsMap = new HashMap<>(1);
                customIdsMap.put("customId", userMap.get(devSn));
                Object o = accessCommandService.delBatchUserInfos(Arrays.asList(Convert.toStrArray(devSn)), customIdsMap, AccessCommandConstant.VERSION);
            }
        }

        if (!freeviewPermissionGroupDeviceList.isEmpty()){
            List<String> devSns = freeviewPermissionGroupDeviceList.stream().map(PermissionGroupDevice::getDevSn).collect(Collectors.toList());
            freeviewCommandBizService.deleteUserInfos(devSns,userList);
        }

        return AjaxResult.success();
    }

    /**
     * 多个访客信息删除
     * @author shd
     * @date 2021/7/8 11:46
     * @param request
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    private AjaxResult visitorsDel(DeviceCommandUserInfoDelRequest request) {
        Long groupId = request.getGroupId();
        List<Long> visitorIds = request.getUserIds();
        List<Visitor> visitorList = visitorService.selectVisitorByIds(visitorIds);
        List<Long> userIds = visitorList.stream().map(Visitor::getUserId).distinct().collect(Collectors.toList());
        Map<Long, List<String>> customIdMap = new HashMap<>();
        visitorList.forEach(item -> {
            customIdMap.computeIfAbsent(item.getUserId(), k -> new ArrayList<>());
            List<String> list = customIdMap.get(item.getUserId());
            list.add(item.getCustomId());
            customIdMap.put(item.getUserId(), list);
        });

        List<UserDevice> userDeviceList = this.getDelUserDevice(userIds, groupId);
        Map<String, List<String>> userMap = new HashMap<>();
        userDeviceList.forEach(item -> {
            userMap.computeIfAbsent(item.getDevSn(), k -> new ArrayList<>());
            List<String> list = userMap.get(item.getDevSn());
            customIdMap.get(item.getUserId()).forEach(i -> {
                list.add(i);
            });
            userMap.put(item.getDevSn(), list);
        });

        if (request.isAsync()) {
            applicationContext.publishEvent(new DelUserBatchCommandEvent(userMap));
            return AjaxResult.success();
        }

        for (String devSn : userMap.keySet()) {
            Map<String, List<String>> customIdsMap = new HashMap<>(1);
            customIdsMap.put("customId", userMap.get(devSn));
            Object o = accessCommandService.delBatchUserInfos(Arrays.asList(Convert.toStrArray(devSn)), customIdsMap, AccessCommandConstant.VERSION);
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult permissionAddDevices(DeviceCommandAddDevicesRequest request) {

        List<AccessDevice> accessDeviceList = accessDeviceService.selectAccessDeviceByIds(request.getDeviceIds());

        List<AccessDevice> hkAccessDeviceList = accessDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HK.equals(item.getModel())).collect(Collectors.toList());
        List<AccessDevice> hqAccessDeviceList = accessDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getModel())).collect(Collectors.toList());

        if (!hkAccessDeviceList.isEmpty()) {
            PermissionGroup permissionGroup = permissionGroupService.selectPermissionGroupById(request.getGroupId());
            List<String> deviceSerials = hkAccessDeviceList.stream().map(AccessDevice::getDevSn).collect(Collectors.toList());
            HikDeviceAddPermissionGroupParam param = new HikDeviceAddPermissionGroupParam();
            param.setGroupId(permissionGroup.getHkGroupId());
            param.setDeviceSerials(deviceSerials);
            hikAccessCommandService.addDevices(param);

            List<PermissionGroupUser> permissionGroupUserList = permissionGroupUserService.selectPermissionGroupUserListByGroupIds(Collections.singletonList(request.getGroupId()));
            List<Long> userIds = permissionGroupUserList.stream().map(PermissionGroupUser::getUserId).collect(Collectors.toList());
            List<User> userList = userMapper.selectUserByIds(userIds,UserConstant.Status.NORMAL);
            List<String> customIds = userList.stream().map(User::getCustomId).collect(Collectors.toList());
            HikPersonAddPermissionGroupParam groupParam = new HikPersonAddPermissionGroupParam();
            groupParam.setGroupId(permissionGroup.getHkGroupId());
            groupParam.setEmployeeNos(customIds);
            hikAccessCommandService.addPersons(groupParam);
        }

        if (!hqAccessDeviceList.isEmpty()) {
            List<PermissionGroupUser> permissionGroupUserList = permissionGroupUserService.selectPermissionGroupUserListByGroupIds(Collections.singletonList(request.getGroupId()));
            List<Long> userIds = permissionGroupUserList.stream().map(PermissionGroupUser::getUserId).distinct().collect(Collectors.toList());
            List<User> userList = userMapper.selectUserByIds(userIds, UserConstant.Status.NORMAL);
            List<String> devSns = hqAccessDeviceList.stream().map(AccessDevice::getDevSn).collect(Collectors.toList());
            applicationContext.publishEvent(new AddDeviceBatchCommandEvent(devSns, userList));
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult permissionDelDevices(DeviceCommandDelDevicesRequest request) {

        List<AccessDevice> accessDeviceList = accessDeviceService.selectAccessDeviceByIds(request.getDeviceIds());

        List<AccessDevice> hkAccessDeviceList = accessDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HK.equals(item.getModel())).collect(Collectors.toList());
        List<AccessDevice> hqAccessDeviceList = accessDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getModel())).collect(Collectors.toList());

        if (!hkAccessDeviceList.isEmpty()) {
            PermissionGroup permissionGroup = permissionGroupService.selectPermissionGroupById(request.getGroupId());
            List<String> deviceSerials = hkAccessDeviceList.stream().map(AccessDevice::getDevSn).collect(Collectors.toList());
            HikDeviceDelPermissionGroupParam param = new HikDeviceDelPermissionGroupParam();
            param.setGroupId(permissionGroup.getHkGroupId());
            param.setDeviceSerials(deviceSerials);
            hikAccessCommandService.delDevices(param);
        }

        if (!hqAccessDeviceList.isEmpty()) {
            List<PermissionGroupUser> groupUsers = permissionGroupUserService.selectPermissionGroupUserListByGroupIds(Collections.singletonList(request.getGroupId()));
            List<Long> userIds = groupUsers.stream().map(PermissionGroupUser::getUserId).collect(Collectors.toList());

            List<UserDevice> userDevices = userDeviceService.selectUserDeviceListByUserIdsAndDeviceIds(null, userIds, request.getDeviceIds());
            List<String> devSns = userDevices.stream().map(UserDevice::getDevSn).distinct().collect(Collectors.toList());
            List<Long> userIdList = userDevices.stream().map(UserDevice::getUserId).collect(Collectors.toList());
            List<User> users = userMapper.selectUserByIds(userIdList, UserConstant.Status.NORMAL);
            List<String> customIds = users.stream().map(User::getCustomId).collect(Collectors.toList());

            applicationContext.publishEvent(new DelDeviceCommandEvent(devSns, customIds));
        }

        return AjaxResult.success();
    }

    @Override
    public void registerHkDeviceAndBindGroups(AccessDevice accessDevice,Boolean isDeviceNeedRegist) {
        //2、统一绑定到hk默认设备组中，并注册设备
        if (accessDevice.getModel().equals("hk") && isDeviceNeedRegist) {
            DeviceAddParam deviceAddParam = new DeviceAddParam("001", accessDevice.getDevSn(), validateCode);
            //海康平台绑定设备
            hkCommandService.addDevice(deviceAddParam);
//            //每个权限组设备绑定设备并下发
//            groupIds.forEach(groupId -> {
//                HikDeviceAddPermissionGroupParam param = new HikDeviceAddPermissionGroupParam();
//                PermissionGroup permissionGroup = permissionGroupService.selectPermissionGroupById(groupId);
//                param.setGroupId(permissionGroup.getHkGroupId());
//                param.setDeviceSerials(Collections.singletonList(accessDevice.getDevSn()));
//                //绑定关系
//                hikAccessCommandService.addDevices(param);
//                //下发人员
//                HikPersonAddPermissionGroupParam groupPersonparam = new HikPersonAddPermissionGroupParam();
//                groupPersonparam.setGroupId(permissionGroup.getHkGroupId());
//
//                PermissionGroupUser permissionGroupUser = new PermissionGroupUser();
//                permissionGroupUser.setGroupId(groupId);
//                List<PermissionGroupUser> permissionGroupUsers = permissionGroupUserService.selectPermissionGroupUserList(permissionGroupUser);
//                List<Long> userIds = permissionGroupUsers.stream().map(PermissionGroupUser::getUserId).collect(Collectors.toList());
//                List<User> userList = userMapper.selectUserByIds(userIds, UserConstant.Status.NORMAL);
//
//                groupPersonparam.setEmployeeNos(userList.stream().map(User::getCustomId).collect(Collectors.toList()));
//                hikAccessCommandService.addPersons(groupPersonparam);
//            });

        }
    }

    @Override
    public AjaxResult addDeviceGroups(AccessDevice accessDevice, List<Long> groupIds,Boolean isDeviceNeedRegist) {
        //3、判断设备是否为海康的设备，如果是海康的设备先注册
        if (accessDevice.getModel().equals(AccessCommandConstant.DeviceType.HK)) {
            this.registerHkDeviceAndBindGroups(accessDevice,isDeviceNeedRegist);
        }

        //单设备多组下发
        if (CollectionUtils.isNotEmpty(groupIds)) {
            groupIds.forEach(groupId -> {
                DeviceCommandAddDevicesRequest deviceCommandAddDevicesRequest = new DeviceCommandAddDevicesRequest();
                deviceCommandAddDevicesRequest.setGroupId(groupId);
                deviceCommandAddDevicesRequest.setDeviceIds(Collections.singletonList(accessDevice.getId()));
                this.permissionAddDevices(deviceCommandAddDevicesRequest);
            });
        }
        return AjaxResult.success();
    }

    /**
     * 删除单设备，多权限组，下发
     *
     * @param device
     * @param groups
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author shd
     * @date 2021/7/13 16:56
     */
    @Override
    public AjaxResult delDeviceGroups(AccessDevice device, List<Long> groups) {

        //1、清除设备、权限组人员关系
        for (Long groupId : groups) {
            DeviceCommandDelDevicesRequest deviceCommandDelDevicesRequest = new DeviceCommandDelDevicesRequest();
            deviceCommandDelDevicesRequest.setGroupId(groupId);
            deviceCommandDelDevicesRequest.setDeviceIds(Collections.singletonList(device.getId()));
            //清除权限组和设备的关系,并删除设备中权限组的人员
            AjaxResult result = this.permissionDelDevices(deviceCommandDelDevicesRequest);
            if (AjaxResult.isError(result)){
                return result;
            }
        }

//        //2、设备类型为海康，还需要删除设备
//        if (device.getModel().equals(AccessCommandConstant.DeviceType.HK) ) {
//            BasicResponse basicResponse = hkCommandService.deleteDevice(device.getDevSn());
//            return BasicResponse.isSuccess(basicResponse) ? AjaxResult.success() : AjaxResult.error(basicResponse.getMessage());
//        }

        return AjaxResult.success();
    }

    /**
     * 查询用户是否有绑定指定类型的设备
     *
     * @param user
     * @param type hq hk
     * @return
     */
    @Override
    public List<AccessDevice> selectUserDeviceByType(User user, String type) {
        List<AccessDevice> accessDeviceList =   accessDeviceService.selectAccessDeviceListByUser( user);
        List<AccessDevice> typeAccessDeviceList = accessDeviceList.stream().filter(item -> type.equals(item.getModel())).collect(Collectors.toList());

        return typeAccessDeviceList;
    }

    /**
     * 删除单用户信息并下发
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult delUserInfo(DeviceCommandDeleteRequest request) {
//
//        User user = userMapper.selectUserById(request.getUserId());
//        List<AccessDevice> accessDeviceList = accessDeviceService.selectAccessDeviceListByUser(user);
//
//        List<AccessDevice> hkDeviceList = accessDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HK.equals(item.getModel())).collect(Collectors.toList());
//        List<AccessDevice> hqDeviceList = accessDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getModel())).collect(Collectors.toList());
//
//        //删除海清人员信息
//        if (!hqDeviceList.isEmpty()) {
//            List<String> devSns = hqDeviceList.stream().map(AccessDevice::getDevSn).distinct().collect(Collectors.toList());
//            if (devSns.isEmpty()) {
//                return AjaxResult.success("删除完成");
//            }
//            Object obj = accessCommandService.delUserInfos(devSns, new SingletonMap("customId",user.getCustomId()), AccessCommandConstant.VERSION);
//
//            AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(obj.toString(), HQResultDTO.class), AccessCommandConstant.FromType.ADMIN);
//            if (returnHQ.get("code").equals(AjaxResult.Type.ERROR)){
//                return returnHQ;
//            }
//        }
//        //删除海康人员信息
//        if (!hkDeviceList.isEmpty()) {
//            BasicResponse basicResponse = hkCommandService.deletePerson(user.getCustomId());
//            if (!BasicResponse.isSuccess(basicResponse)){
//                return AjaxResult.error("海康：删除用户信息失败，用户编号为："+ user.getId() + ",名称:" + user.getUserName());
//            }
//        }
//
//        return AjaxResult.success();

        User user = userMapper.selectUserById(request.getUserId());

        List<AccessDevice> accessDeviceList =   accessDeviceService.selectAccessDeviceListByUser( user);
        List<AccessDevice> hqDeviceList = accessDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getModel())).collect(Collectors.toList());
        List<AccessDevice> freeviewDeviceList = accessDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.FREEVIEW_45.equals(item.getModel())).collect(Collectors.toList());


        if (!hqDeviceList.isEmpty()) {
            List<String> devSns = freeviewDeviceList.stream().map(AccessDevice::getDevSn).collect(Collectors.toList());
            Map<String, List<String>> customIdsMap = new HashMap<>(1);
            customIdsMap.put("customId", Collections.singletonList(user.getCustomId()));
            Object o = accessCommandService.delUserInfos(devSns, new SingletonMap("customId",user.getCustomId()), AccessCommandConstant.VERSION);
            AjaxResult returnHQ =  this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), null);
            if (AjaxResult.isError(returnHQ)){
                return returnHQ;
            }
        }

        if (!freeviewDeviceList.isEmpty()){
            List<String> devSns = freeviewDeviceList.stream().map(AccessDevice::getDevSn).collect(Collectors.toList());
            Object o = freeviewCommandBizService.deleteUserInfo(devSns, user);
            AjaxResult returnHQ =  this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), null);
            if (AjaxResult.isError(returnHQ)){
                return returnHQ;
            }
        }

        return AjaxResult.success();
    }

    /**
     * @param request
     * @description: 删除用户下发到设备
     * @author taojc
     * @date: 2022/8/17
     */
    @Override
    public void delUserDeviceInfos(DeviceCommandDeleteRequest request) {
        User user = userMapper.selectUserById(request.getUserId());

        List<AccessDevice> accessDeviceList = accessDeviceService.selectAccessDeviceListByUser(user);
        List<AccessDevice> hqDeviceList = accessDeviceList.stream()
                .filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getModel()))
                .collect(Collectors.toList());

        List<AccessDevice> freeviewDeviceList = accessDeviceList.stream()
                .filter(e ->Arrays.asList(AccessCommandConstant.DeviceType.FREEVIEW_45,AccessCommandConstant.DeviceType.FREEVIEW_32).contains(e.getModel()))
                .collect(Collectors.toList());


        if (!hqDeviceList.isEmpty()) {
            List<String> devSns = hqDeviceList.stream().map(AccessDevice::getDevSn).collect(Collectors.toList());
            Map<String, List<String>> customIdsMap = new HashMap<>(1);
            customIdsMap.put("customId", Collections.singletonList(user.getCustomId()));
            Object o = accessCommandHQService.delBatchUserInfos(devSns, customIdsMap, AccessCommandConstant.VERSION);
            AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), null);
        }

        if (!freeviewDeviceList.isEmpty()) {
            List<String> devSns = freeviewDeviceList.stream().map(AccessDevice::getDevSn).collect(Collectors.toList());
            Object o = freeviewCommandBizService.deleteUserInfo(devSns, user);
            log.info("删除设备result:{}",o);
            AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), null);
        }

    }

    @Override
    public AjaxResult delUserInfobatch(DeviceCommandDeleteRequest request) {
        return null;
    }

    @Override
    public AjaxResult addUpdatePersionCommand(User user, String type, Boolean personUpdateNeedSyncHk) {
        //如果是海康的设备，新增用户时先新增用户信息，再调用权限组下发
        List<AccessDevice> hkDeviceList = this.selectUserDeviceByType(user, AccessCommandConstant.DeviceType.HK);
        if (!hkDeviceList.isEmpty()) {
            AjaxResult result = this.addUpdateHkPersonBaseInfo(user,type,personUpdateNeedSyncHk);
            if (AjaxResult.isError(result)){
                return result;
            }
        }

        //根据用户的设备类型，走对应的设备下发流程
        DeviceCommandUserInfoDownloadRequest request = new DeviceCommandUserInfoDownloadRequest();
        request.setUserId(user.getId());
        request.setAsync(true);
        AjaxResult result = this.userInfoDownload(request);
        return result;
    }

    @Override
    public AjaxResult addUpdateHkPersonBaseInfo(User user,String type,Boolean personUpdateNeedSyncHk){
        if ("add".equals(type)) {
            PersonAddParam personAddParam = userPersonConvert.convertUser2PersonAdd(user);
            PersonResponse personResponse = hkCommandService.addPerson(personAddParam);
            if (!BasicResponse.isSuccess(personResponse)) {
                return AjaxResult.error(personResponse.getMessage());
            }
            user.setHkRegistFlag(1);
            userMapper.updateUser(user);
        } else if ("update".equals(type) && personUpdateNeedSyncHk) {
            //修改人员基础信息
            PersonUpdateParam personUpdateParam = userPersonConvert.convertUser2PersonUpdate(user);
            BasicResponse updateResponse = hkCommandService.updatePerson(personUpdateParam);
            //如果修改人员时，返回人员没注册编码，重新注册人员
            if (updateResponse.getCode().equals(AccessCommandConstant.HkResponse.PERSION_NOT_EXIST)) {
                PersonAddParam personAddParam = userPersonConvert.convertUser2PersonAdd(user);
                PersonResponse addResponse = hkCommandService.addPerson(personAddParam);
                if (!BasicResponse.isSuccess(addResponse)) {
                    return AjaxResult.error("海康:人员注册失败：" + user.getId() + "-" + user.getUserName());
                }
                user.setHkRegistFlag(1);
                userMapper.updateUser(user);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 人员列表点击下发
     *
     * @param user
     * @return
     */
    @Override
    public AjaxResult personCardCommand(User user) {

        //如果是海康的设备，新增用户时先新增用户信息，再调用权限组下发
        List<AccessDevice> hkDeviceList = this.selectUserDeviceByType(user, AccessCommandConstant.DeviceType.HK);
        if (!hkDeviceList.isEmpty()) {
            //1、查询用户基础信息是否已经下发
            PersonResponse personDetail = hkCommandService.getPersonDetail(user.getCustomId());
            if (personDetail.getCode().equals(AccessCommandConstant.HkResponse.PERSION_NOT_EXIST)) {
                //人员不存在，需要下发基础信息
                PersonAddParam personAddParam = userPersonConvert.convertUser2PersonAdd(user);
                PersonResponse personResponse = hkCommandService.addPerson(personAddParam);
                log.info(personResponse.toString());
            }
        }

        //根据用户的设备类型，走对应的设备下发流程
        DeviceCommandUserInfoDownloadRequest request = new DeviceCommandUserInfoDownloadRequest();
        request.setUserId(user.getId());
        request.setAsync(false);
        if (StringUtils.isNotEmpty(user.getPermissionGroup())){
            request.setGroupId(Long.valueOf(user.getPermissionGroup()));
        }
        AjaxResult result = this.userInfoDownload(request);
        return result;
    }

    @Override
    public AjaxResult personCardCommand(User user, DCard dCard, String commandType) {
        //根据用户的设备类型，走对应的设备下发流程
        DeviceCommandUserInfoDownloadRequest request = new DeviceCommandUserInfoDownloadRequest();
        request.setUserId(user.getId());
        request.setAsync(false);
        AjaxResult result = this.userCardInfoDownload(request,dCard,commandType);
        return result;
    }

    @Override
    public PermissionGroupResponse addGroup(Long groupId) {
        PermissionGroup permissionGroup = permissionGroupService.selectPermissionGroupById(groupId);
        HikPermissionGroupAddParam param = new HikPermissionGroupAddParam();
        param.setGroupName(permissionGroup.getGroupName());
        return hikAccessCommandService.addPermissionGroup(param);
    }

    /**
     * 门禁远程开门
     * 1、判断设备是否在线，不在线，直接返回离线；
     * 2、发送开门命令
     * @param accessDevice
     * @return
     */
    @Override
    public AjaxResult openDoor(AccessDevice accessDevice, Long operator) {
        if(StringUtils.isEmpty(accessDevice.getOnlineStatus()) || "offline".equals(accessDevice.getOnlineStatus())){
            return AjaxResult.error("设备离线");
        }
        Object obj = accessCommandService.openDoor(accessDevice.getDevSn(),AccessCommandConstant.DeviceType.HQ,AccessCommandConstant.VERSION);
        AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(obj.toString(), HQResultDTO.class), AccessCommandConstant.FromType.ADMIN);
        if (returnHQ.get("code").equals(AjaxResult.Type.ERROR)){
            return returnHQ;
        }
        return AjaxResult.success();
    }


}
